import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

export const useMapStore = defineStore('map', () => {
  // 地图实例
  const mapInstance = ref(null)
  
  // 当前绘制模式
  const drawMode = ref('none') // none, point, line, polygon, circle, rectangle
  
  // 图层列表
  const layers = reactive([])
  
  // 当前选中的图层
  const selectedLayer = ref(null)
  
  // 地图配置
  const mapConfig = reactive({
    center: [39.908823, 116.397470], // 北京
    zoom: 12,
    minZoom: 3,
    maxZoom: 18
  })
  
  // 固定起点（天安门，经纬度与 defaultMapConfig 对齐）
  const startPoint = ref({ lat: 39.908823, lng: 116.397470, name: '天安门' })
  
  // 随机生成/导入的点集合（用于可视化与排序）
  const generatedPoints = reactive([])
  
  // 路径顺序（使用点的 id 列表记录，便于稳定映射展示）
  const originalOrder = ref([])
  const optimizedOrder = ref([])
  
  // 绘制工具状态
  const drawState = reactive({
    isDrawing: false,
    currentShape: null,
    tempPoints: []
  })
  
  // 设置地图实例
  const setMapInstance = (map) => {
    mapInstance.value = map
  }
  
  // 设置绘制模式
  const setDrawMode = (mode) => {
    drawMode.value = mode
    drawState.isDrawing = mode !== 'none'
    drawState.tempPoints = []
    
    console.log('设置绘制模式:', mode, '是否绘制中:', drawState.isDrawing)
  }
  
  // 添加图层
  const addLayer = (layer) => {
    layers.push(layer)
  }
  
  // 删除图层
  const removeLayer = (layerId) => {
    const index = layers.findIndex(layer => layer.id === layerId)
    if (index > -1) {
      layers.splice(index, 1)
    }
  }
  
  // 选择图层
  const selectLayer = (layer) => {
    selectedLayer.value = layer
  }
  
  // 更新地图配置
  const updateMapConfig = (config) => {
    Object.assign(mapConfig, config)
  }

  // 设置生成的点集合
  const setGeneratedPoints = (points) => {
    generatedPoints.length = 0
    for (const p of points) generatedPoints.push(p)
  }

  // 清空生成点
  const clearGeneratedPoints = () => {
    generatedPoints.length = 0
  }

  // 设置路径顺序
  const setOriginalOrder = (ids) => { originalOrder.value = Array.isArray(ids) ? ids.slice() : [] }
  const setOptimizedOrder = (ids) => { optimizedOrder.value = Array.isArray(ids) ? ids.slice() : [] }
  const clearOrders = () => { originalOrder.value = []; optimizedOrder.value = [] }
  
  // 添加绘制点
  const addDrawPoint = (point) => {
    drawState.tempPoints.push(point)
    console.log('添加绘制点:', point, '当前点数:', drawState.tempPoints.length)
  }
  
  // 清除绘制状态
  const clearDrawState = () => {
    drawState.isDrawing = false
    drawState.currentShape = null
    drawMode.value = 'none'
    drawState.tempPoints = []
  }
  
  return {
    // 状态
    mapInstance,
    drawMode,
    layers,
    selectedLayer,
    mapConfig,
    startPoint,
    generatedPoints,
    originalOrder,
    optimizedOrder,
    drawState,
    
    // 方法
    setMapInstance,
    setDrawMode,
    addLayer,
    removeLayer,
    selectLayer,
    updateMapConfig,
    setGeneratedPoints,
    clearGeneratedPoints,
    setOriginalOrder,
    setOptimizedOrder,
    clearOrders,
    addDrawPoint,
    clearDrawState
  }
}) 